package com.chh2000day.mirai.plugin

import com.chh2000day.mirai.plugin.base.GroupMapper
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import net.mamoe.mirai.console.plugin.jvm.JvmPluginDescription
import net.mamoe.mirai.console.plugin.jvm.KotlinPlugin
import net.mamoe.mirai.console.util.ConsoleExperimentalApi
import net.mamoe.mirai.event.events.MemberJoinEvent
import net.mamoe.mirai.event.globalEventChannel
import okio.buffer
import okio.source
import java.io.File

@ConsoleExperimentalApi
object AddGroupReply : KotlinPlugin(JvmPluginDescription.loadFromResource()) {
    private lateinit var config: Config
    private val STORE_FILE = File(configFolder, "addGroupReply.json")
    private val json = Json {
        isLenient = true
        prettyPrint = true
    }

    override fun onEnable() {
        super.onEnable()

        logger.info("Plugin loaded!")

        kotlin.runCatching {
            synchronized(STORE_FILE) {
                val source = STORE_FILE.source().buffer()
                val confStr = source.readUtf8()
                source.close()
                config = runCatching { json.decodeFromString(Config.serializer(), confStr) }.getOrElse {
                    logger.error("加载加群回复json失败!将使用空白配置", it)
                    Config(mutableListOf())
                }
            }
        }.exceptionOrNull()?.let {
            logger.error("读取json文件失败", it)
            config = Config(mutableListOf())
        }
        globalEventChannel().subscribeAlways<MemberJoinEvent> {
            config.groupConf.forEach { groupConfig ->
                groupConfig.groupNames.forEach {
                    if (this.group.id == GroupMapper.getIdByName(it)) {
                        this.group.sendMessage(
                            groupConfig.message.parseCode(this.group, this.member)
                        )
                    }
                }
            }
        }
    }

    @Serializable
    data class GroupConfig(val groupNames: List<String>, val message: String)

    @Serializable
    data class Config(val groupConf: List<GroupConfig>)
}